package org.deng.learn.mybatis.interceptor;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;

import java.sql.Connection;
import java.util.Enumeration;
import java.util.Properties;

/**
 * @Author DengLibin
 * @Date 19-4-27
 * @Time 下午11:12
 * @Desc mybatis 拦截器
 */
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
public class MyInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        StatementHandler statementHandler=(StatementHandler)invocation.getTarget();
        System.out.println("StatementHandler:"+statementHandler.getClass().getName());
        MetaObject metaStatementHandler = SystemMetaObject.forObject(statementHandler);

        //获取sql
        String sql= String.valueOf(metaStatementHandler.getValue("delegate.boundSql.sql"));
        //添加limit条件
        //sql="select * from (" + sql + ") as temp limit 1";
        System.out.println("拦截sql语句:"+sql);
        //重新设置sql
        metaStatementHandler.setValue("delegate.boundSql.sql",sql);
        return invocation.proceed();

    }

    @Override
    public Object plugin(Object target) {
        System.out.println("plugin方法参数："+target.getClass().getName());
        //该方法会调用多次，参数类型如下：
        //org.apache.ibatis.executor.CachingExecutor
        //org.apache.ibatis.scripting.defaults.DefaultParameterHandler
        //org.apache.ibatis.executor.resultset.DefaultResultSetHandler
        //org.apache.ibatis.executor.statement.RoutingStatementHandler
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        System.out.println("setProperties方法");
        //String dialect = properties.getProperty("dialect");
        Enumeration<Object> keys = properties.keys();
        System.out.println("keys:"+keys.getClass().getName());
    }
}
